# etbox_gui.py - GUI界面
# coder DarionDong

import tkinter as tk
from tkinter import messagebox, filedialog, scrolledtext
import threading
import time
import os
import json
import subprocess
import sys

class ETBOXGUI:
    def __init__(self):
        self.root = None
        self.config_file = os.path.join(os.path.expanduser("~"), ".etbox_service.json")
    
    def show_main_gui(self):
        """显示主GUI界面"""
        self.root = tk.Tk()
        self.root.title("ETBOX上传工具 v2.0")
        self.root.geometry("500x400")
        self.root.resizable(False, False)
        
        # 设置图标
        try:
            self.root.iconbitmap("etbox.ico")
        except:
            pass
        
        # 标题
        title_frame = tk.Frame(self.root, bg="#2c3e50", height=80)
        title_frame.pack(fill="x")
        title_frame.pack_propagate(False)
        
        tk.Label(title_frame, text="📦 ETBOX上传工具", 
                font=("Arial", 16, "bold"), fg="white", bg="#2c3e50").pack(expand=True)
        tk.Label(title_frame, text="后台服务 + 右键上传", 
                font=("Arial", 10), fg="#ecf0f1", bg="#2c3e50").pack()
        
        # 主内容区域
        main_frame = tk.Frame(self.root)
        main_frame.pack(fill="both", expand=True, padx=20, pady=20)
        
        # 服务管理
        service_frame = tk.LabelFrame(main_frame, text="🔧 服务管理", font=("Arial", 10, "bold"), padx=15, pady=10)
        service_frame.pack(fill="x", pady=(0, 10))
        
        tk.Button(service_frame, text="🚀 启动后台服务", 
                 command=self.start_service, width=15, height=2,
                 bg="#27ae60", fg="white", font=("Arial", 9, "bold")).pack(side="left", padx=5)
        tk.Button(service_frame, text="🛑 停止后台服务", 
                 command=self.stop_service, width=15, height=2,
                 bg="#e74c3c", fg="white", font=("Arial", 9, "bold")).pack(side="left", padx=5)
        
        # 服务状态
        self.service_status = tk.Label(service_frame, text="❓ 服务状态: 未知", font=("Arial", 9))
        self.service_status.pack(side="left", padx=20)
        
        # 右键菜单管理
        menu_frame = tk.LabelFrame(main_frame, text="📌 右键菜单管理", font=("Arial", 10, "bold"), padx=15, pady=10)
        menu_frame.pack(fill="x", pady=(0, 10))
        
        menu_btn_frame = tk.Frame(menu_frame)
        menu_btn_frame.pack(fill="x")
        
        tk.Button(menu_btn_frame, text="➕ 添加右键菜单", 
                 command=self.add_right_click, width=16, height=2).pack(side="left", padx=5)
        tk.Button(menu_btn_frame, text="🗑️ 移除右键菜单", 
                 command=self.remove_right_click, width=16, height=2).pack(side="left", padx=5)
        
        # 功能操作
        func_frame = tk.LabelFrame(main_frame, text="🚀 功能操作", font=("Arial", 10, "bold"), padx=15, pady=10)
        func_frame.pack(fill="both", expand=True)
        
        # 文件上传
        upload_frame = tk.Frame(func_frame)
        upload_frame.pack(fill="x", pady=5)
        
        tk.Label(upload_frame, text="文件上传:", font=("Arial", 9, "bold")).pack(anchor="w")
        
        tk.Button(upload_frame, text="📎 选择文件上传", 
                 command=self.upload_file_dialog, width=16, height=2,
                 bg="#3498db", fg="white", font=("Arial", 9, "bold")).pack(anchor="w", pady=5)
        
        # 消息发送
        msg_frame = tk.Frame(func_frame)
        msg_frame.pack(fill="both", expand=True, pady=5)
        
        tk.Label(msg_frame, text="消息发送:", font=("Arial", 9, "bold")).pack(anchor="w")
        
        self.msg_text = scrolledtext.ScrolledText(msg_frame, height=4, width=50, font=("Arial", 9))
        self.msg_text.pack(fill="both", expand=True, pady=5)
        
        tk.Button(msg_frame, text="💬 发送消息", 
                 command=self.send_message, width=12).pack()
        
        # 初始检查服务状态
        self.check_service_status()
        
        self.root.mainloop()
    
    def start_service(self):
        """启动后台服务"""
        try:
            # 使用subprocess启动服务
            if getattr(sys, 'frozen', False):
                # 打包后的exe
                exe_path = sys.executable
                subprocess.Popen([exe_path, "service"], creationflags=subprocess.CREATE_NO_WINDOW)
            else:
                # Python脚本
                subprocess.Popen([sys.executable, "main.py", "service"], creationflags=subprocess.CREATE_NO_WINDOW)
            
            messagebox.showinfo("成功", "后台服务已启动")
            self.check_service_status()
        except Exception as e:
            messagebox.showerror("错误", f"启动服务失败: {e}")
    
    def stop_service(self):
        """停止后台服务"""
        # 这里需要实现停止服务的逻辑
        # 可以通过发送停止信号或查找进程并终止
        messagebox.showinfo("信息", "停止服务功能待实现")
    
    def check_service_status(self):
        """检查服务状态"""
        # 这里实现检查服务是否运行的逻辑
        self.service_status.config(text="✅ 服务状态: 运行中")
    
    def add_right_click(self):
        """添加右键菜单"""
        try:
            import winreg
            
            # 获取当前脚本路径
            if getattr(sys, 'frozen', False):
                script_path = sys.executable
            else:
                script_path = os.path.abspath(__file__)
                python_exe = sys.executable
                script_path = f'"{python_exe}" "{script_path}"'
            
            # 添加右键菜单
            menu_name = "上传到ETBOX"
            
            # 为所有文件添加
            key_path = f"Software\\Classes\\*\\shell\\{menu_name}"
            key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, key_path)
            winreg.SetValueEx(key, "Icon", 0, winreg.REG_SZ, script_path)
            winreg.CloseKey(key)
            
            command_path = f"{key_path}\\command"
            command_key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, command_path)
            command_value = f'"{script_path}" upload "%1"'
            winreg.SetValueEx(command_key, "", 0, winreg.REG_SZ, command_value)
            winreg.CloseKey(command_key)
            
            messagebox.showinfo("成功", "右键菜单添加成功！")
            
        except Exception as e:
            messagebox.showerror("错误", f"添加右键菜单失败: {e}")
    
    def remove_right_click(self):
        """移除右键菜单"""
        try:
            import winreg
            
            menu_name = "上传到ETBOX"
            
            # 移除所有文件类型的菜单
            key_path = f"Software\\Classes\\*\\shell\\{menu_name}"
            try:
                winreg.DeleteKey(winreg.HKEY_CURRENT_USER, f"{key_path}\\command")
                winreg.DeleteKey(winreg.HKEY_CURRENT_USER, key_path)
            except WindowsError:
                pass
            
            messagebox.showinfo("成功", "右键菜单移除成功")
            
        except Exception as e:
            messagebox.showerror("错误", f"移除右键菜单失败: {e}")
    
    def upload_file_dialog(self):
        """文件上传对话框"""
        file_path = filedialog.askopenfilename(title="选择要上传的文件")
        if file_path:
            from etbox_client import handle_upload_request
            handle_upload_request(file_path)
    
    def send_message(self):
        """发送消息"""
        message = self.msg_text.get("1.0", "end-1c").strip()
        if not message:
            messagebox.showwarning("警告", "请输入消息内容")
            return
        
        # 这里实现发送消息的逻辑
        messagebox.showinfo("成功", "消息发送功能待实现")
        self.msg_text.delete("1.0", tk.END)

def show_main_gui():
    """显示主GUI"""
    gui = ETBOXGUI()
    gui.show_main_gui()